import storage from "@/utils/storage";
import { login, getInfo, logout } from "@/api/user.js";
import { resetRouter } from "@/router/router.js";

export default {
	namespaced: true,
	state: {
		token: storage('token').get(),
		name: "",
		avatar: "",
		introduction: "",
		roles: [],
	},
	mutations: {
		setToken: (state, token) => {
			state.token = token;
		},
		setIntroduction: (state, introduction) => {
			state.introduction = introduction;
		},
		setName: (state, name) => {
			state.name = name;
		},
		setAvatar: (state, avatar) => {
			state.avatar = avatar;
		},
		setRoles: (state, roles) => {
			state.roles = roles;
		},
	},
	actions: {
		// 登录
		login({ commit }, form) {
			return new Promise((resolve, reject) => {
				login(form)
					.then(res => {
						commit("setToken", res.token);
						storage('token').set(res.token)
						resolve(res);
					})
					.catch(error => {
						reject(error);
					});
			});
		},
		// 获取用户信息
		getInfo({ commit, state }) {
			return new Promise((resolve, reject) => {
				getInfo(state.token)
					.then(res => {
						const { roles, name, avatar, introduction } = res;
						commit("setRoles", roles);
						commit("setName", name);
						commit("setAvatar", avatar);
						commit("setIntroduction", introduction);
						resolve({ roles, name, avatar, introduction });
					})
					.catch(error => {
						reject(error);
					});
			});
		},
		// 退出登录
		logout({ commit }) {
			return new Promise((resolve, reject) => {
				logout()
					.then(() => {
						commit("setToken", "");
						commit("setRoles", []);
						storage('token').remove()
						resetRouter();
						resolve();
					})
					.catch(error => {
						reject(error);
					});
			});
		},
	},
};
